/*
 * @Author: hongbin
 * @Date: 2022-11-22 00:04:35
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-30 20:25:18
 * @Description:好友展示
 */
import { FC, useCallback, useEffect, useMemo, useRef, useState } from "react";
import styled, { css } from "styled-components";
import { get, post } from "../../../api";
import { UserInfo } from "../../../hook/useRegisterForm";
import { SocketManager } from "../../../socket";
import ChatRecord from "./ChatRecord";
import FriendsHead from "./FriendsHead";

interface IProps {
    user: UserInfo;
    open: boolean;
}

export interface Message {
    sender: string;
    content: string;
    type: string;
    date: number;
}

export interface IChatRecord {
    [key: string]: Message[];
}

const Friends: FC<IProps> = ({ user, open }) => {
    const [list, setList] = useState<Array<UserInfo>>([]);
    const [currChatId, setCurrChatId] = useState("");
    const [haveNewMessage, setHaveNewMessage] = useState<Record<string, boolean>>({});
    const [record, setRecord] = useState<IChatRecord>({});
    const chatRecordId = useMemo(
        () => user.friendsList.find((f) => f.friendId == currChatId)?.chatRecordId,
        [currChatId, user.friendsList]
    );
    const currChatIdRef = useRef(currChatId);

    useEffect(() => {
        const listen = (d: any) => {
            console.log("朋友发消息给我：", d);
            const msg = {
                content: d.content,
                type: d.type,
                sender: d.sender,
                date: d.date,
            };
            setRecord((prev) => ({
                ...prev,
                [d.sender]: prev[d.sender] ? [...prev[d.sender], msg] : [msg],
            }));
            if (currChatIdRef.current != msg.sender) {
                //为发消息的朋友设置新消息标志
                setHaveNewMessage((prev) => ({ ...prev, [msg.sender]: true }));
            }
        };
        SocketManager.listen("friendSendMessageToMe", listen);
        return () => {
            // SocketManager.removeListen("friendSendMessageToMe", listen);
        };
    }, []);

    const queryFriendsList = useCallback(async () => {
        // console.log("好友基本信息:", user.friendsList);

        const { data } = await post("/FriendsList/queryFriendsInfo", {
            friendsList: user.friendsList,
            userId: user._id,
        });
        setList(data);
        // console.log("好友信息：", data);
    }, [user]);

    useEffect(() => {
        queryFriendsList();
        //移除监听
        return () => {};
    }, [queryFriendsList]);

    const toggleChat = useCallback((user: UserInfo) => {
        console.log("切换与" + user.name + "对话");
        setCurrChatId(user._id);
    }, []);

    /**
     * 查询与某用户的聊天记录
     */
    const queryChatRecord = useCallback(
        async (otherId: string) => {
            console.log("聊天室id:", chatRecordId);
            if (!chatRecordId) return new Error("未获取到该用户信息！");

            const { data } = await get("/ChatRecord/query?id=" + chatRecordId);
            console.log("聊天记录", data.record);
            setRecord((prev) => ({ ...prev, [otherId]: data.record }));
        },
        [chatRecordId]
    );

    useEffect(() => {
        if (currChatId) {
            console.log("查询与" + currChatId + "的聊天记录");
            currChatIdRef.current = currChatId;
            queryChatRecord(currChatId);
            //取消该朋友的新消息
            setHaveNewMessage((prev) => ({ ...prev, [currChatId]: false }));
        }
    }, [currChatId, queryChatRecord]);

    const sendMessage = useCallback(
        async (content: string) => {
            const msg = {
                content,
                type: "text",
                sender: user._id,
                date: Date.now(),
            };
            console.log("发送消息：", msg);
            //数据保存recordId
            const postMsg = { ...msg, recordId: chatRecordId };
            const { data } = await post("/ChatRecord/sendMessage", postMsg);
            //本地添加
            setRecord((prev) => ({ ...prev, [currChatId]: [...prev[currChatId], msg] }));
            //socket通知
            SocketManager.emit("sendMessageToFriend", { ...postMsg, to: currChatId });
            console.log("发送结果:", data);
        },
        [chatRecordId, currChatId, user._id]
    );

    return (
        <Container open={open}>
            <FriendsHead haveNewMessage={haveNewMessage} active={currChatId} onChange={toggleChat} list={list} />
            {currChatId && <ChatRecord sendMessage={sendMessage} msgs={record[currChatId]} />}
        </Container>
    );
};

export default Friends;

const Container = styled.div<{ open: boolean }>`
    width: 100%;
    height: 100%;
    /* background: #faa; */
    opacity: 0;
    transition: 0.3s;
    visibility: hidden;
    ${({ open }) =>
        open &&
        css`
            opacity: 1;
            visibility: visible;
        `}
`;
